//
//  ScanViewController.swift
//  TalkeTv
//
//  Created by lhf on 2024/10/15.
//

import AVFoundation
import UIKit

class ScanViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    var captureSession: AVCaptureSession!
    var previewLayer: AVCaptureVideoPreviewLayer!
    var scanResBlock:((_ qrcode: String) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .black
        captureSession = AVCaptureSession()
        
        guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else {
            failed()
            return
        }
        
        let videoInput: AVCaptureDeviceInput
        
        do {
            videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
        } catch {
            failed()
            return
        }
        
        if captureSession.canAddInput(videoInput) {
            captureSession.addInput(videoInput)
        } else {
            failed()
            return
        }
        
        let metadataOutput = AVCaptureMetadataOutput()
        
        if captureSession.canAddOutput(metadataOutput) {
            captureSession.addOutput(metadataOutput)
            
            metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            metadataOutput.metadataObjectTypes = [.qr, .ean8, .ean13, .pdf417, .upce, .code39, .code128]
        } else {
            failed()
            return
        }
        
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer.frame = view.layer.bounds
        previewLayer.videoGravity = .resizeAspectFill
        view.layer.addSublayer(previewLayer)
        
        DispatchQueue.global(qos: .userInitiated).async {
            self.captureSession.startRunning()
        }
        
        // 添加扫描框
        let scanFrame = UIView()
        scanFrame.layer.borderColor = UIColor.green.cgColor
        scanFrame.layer.borderWidth = 2
        scanFrame.frame = CGRect(x: view.frame.midX - 150,
                                y: view.frame.midY - 150,
                                width: 300,
                                height: 300)
        view.addSubview(scanFrame)
        
        // 添加扫描线动画
        let scanLine = UIView()
        scanLine.frame = CGRect(x: scanFrame.frame.minX,
                               y: scanFrame.frame.minY,
                               width: scanFrame.frame.width,
                               height: 2)
        scanLine.backgroundColor = .green
        view.addSubview(scanLine)
        
        UIView.animate(withDuration: 2.0, delay: 0, options: [.repeat, .autoreverse], animations: {
            scanLine.frame.origin.y = scanFrame.frame.maxY - 2
        }, completion: nil)
        
        // 添加提示标签
        let hintLabel = UILabel()
        hintLabel.text = "将二维码/条形码放入框内"
        hintLabel.textColor = .white
        hintLabel.textAlignment = .center
        hintLabel.frame = CGRect(x: scanFrame.frame.minX,
                                y: scanFrame.frame.maxY + 20,
                                width: scanFrame.frame.width,
                                height: 30)
        view.addSubview(hintLabel)
        
        let leftBtn:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "icon_nav_left_black"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.backPage(_:)))
        leftBtn.tintColor = UIColor.white
        self.navigationItem.leftBarButtonItem = leftBtn

    }
    
    @objc func backPage(_ btn: UIButton) {
        self.dismiss(animated: true)
    }
    
    func failed() {
        let ac = UIAlertController(title: "Scanning not supported",
                                  message: "Your device does not support scanning a code from an item. Please use a device with a camera.",
                                  preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
        captureSession = nil
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if captureSession?.isRunning == false {
            DispatchQueue.global(qos: .userInitiated).async {
                self.captureSession.startRunning()
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        if captureSession?.isRunning == true {
            captureSession.stopRunning()
        }
    }
    
    func metadataOutput(_ output: AVCaptureMetadataOutput,
                        didOutput metadataObjects: [AVMetadataObject],
                        from connection: AVCaptureConnection) {
        captureSession.stopRunning()
        
        if let metadataObject = metadataObjects.first {
            guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
            guard let stringValue = readableObject.stringValue else { return }
            AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
            found(code: stringValue)
        }
        
        dismiss(animated: true)
    }
    
    func found(code: String) {
        print("Scanned code: \(code)")
        // 处理扫描到的二维码/条形码
        print("扫码结果：\(code)")
        self.view.makeToast("扫描成功", duration: 1.0, position: .center)
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            self.dismiss(animated: false)
            if self.scanResBlock != nil {
                self.scanResBlock!(code)
            }
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}
